﻿using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace System.Lua.Converters
{
    internal class StringConverter : LuaTypeConverter<System.ComponentModel.StringConverter>
    {
        private static readonly Dictionary<char, string> EscapeCodes = InitializeEscapeCodes();
        private static readonly Regex CharRegex = new Regex("[" + new String(EscapeCodes.Keys.ToArray()) + "]", RegexOptions.Compiled);

        private static Dictionary<char, string> InitializeEscapeCodes()
        {
            return new Dictionary<char, string>
                   {
                        { 'õ', @"\195\181" },
                        { 'ő', @"\195\181" },
                        { 'à', @"\195\160" },
                        { 'á', @"\195\161" },
                        { 'â', @"\195\162" },
                        { 'ã', @"\195\163" },
                        { 'ä', @"\195\164" },
                        { 'æ', @"\195\166" },
                        { 'ç', @"\195\167" },
                        { 'Ä', @"\195\132" },
                        { 'Ö', @"\195\150" },
                        { 'Ü', @"\195\156" },
                        { 'ß', @"\195\159" },
                        { 'è', @"\195\168" },
                        { 'é', @"\195\169" },
                        { 'ê', @"\195\170" },
                        { 'ë', @"\195\171" },
                        { 'ì', @"\195\172" },
                        { 'í', @"\195\173" },
                        { 'î', @"\195\174" },
                        { 'ï', @"\195\175" },
                        { 'ò', @"\195\178" },
                        { 'ó', @"\195\179" },
                        { 'ô', @"\195\180" },
                        { 'ù', @"\195\185" },
                        { 'ú', @"\195\186" },
                        { 'û', @"\195\187" },
                        { 'ű', @"\195\187" },
                        { 'ü', @"\195\188" },
                        { 'ñ', @"\195\177" },
                        { 'ö', @"\195\182" },
                        { 'ø', @"\195\184" },
                        { 'œ', @"\197\147" }
                   };
        }

        public override object ConvertTo(object value, Type targetType)
        {
            if (value == null)
                throw new ArgumentNullException("value");
            if (value.GetType() != typeof(String))
                throw new ArgumentException("Value type mismatch", @"value");

            var stringValue = (string)value;

            // Replace all matches of the regular expression with the correct escape code
            return CharRegex.Replace(stringValue, x => EscapeCodes[x.Value[0]]);
        }
    }
}
